package com.after.saas.common.utils;


import cn.hutool.core.collection.CollectionUtil;
import com.after.saas.common.model.TreeEntity;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname MenuTreeUtil
 * @Description TODO
 * @auth after
 * @since 2021/8/21 15:11
 */

@UtilityClass
public class MenuTreeUtil {

    //建立树形结构
    public <T extends TreeEntity> List<T> buildTree(List<T> menuList) {
        List<T> treeMenus = new ArrayList<>();
        for (T menuTreeNode : getRootNode(menuList)) {
            menuTreeNode = buildChildrenTree(menuList, menuTreeNode);
            treeMenus.add(menuTreeNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    public <T extends TreeEntity> T buildChildrenTree(List<T> menuList, T pNode) {
        List<T> children = new ArrayList<>();
        for (T menuTreeNode : menuList) {
            if (pNode.getId().equals(menuTreeNode.getParentId())) {
                children.add(buildChildrenTree(menuList, menuTreeNode));
            }
        }
        if (CollectionUtil.isNotEmpty(children)) {
            pNode.setHasChildren(true);
        }
        pNode.setChildren(children);
        return pNode;
    }

    //递归，遍历子树形结构
    public <T extends TreeEntity> List<String> getChildrenTree(List<String> menuList, T pNode) {
        if (pNode.isHasChildren()) {
            List<T> list = pNode.getChildren();
            for (T menu : list) {
                menuList.add(menu.getId());
                if (menu.isHasChildren()) {
                    getChildrenTree(menuList, menu);
                }
            }
        }
        return menuList;
    }

    //获取根节点
    public <T extends TreeEntity> List<T> getRootNode(List<T> menuList) {
        List<T> rootMenuLists = new ArrayList<>();
        for (T menu : menuList) {
            if ("0".equals(menu.getParentId())) {
                rootMenuLists.add(menu);
            }
        }
        return rootMenuLists;
    }
}
